package cn.tedu.dao.impl;

import java.util.List;

import cn.tedu.dao.UserDao;
import cn.tedu.dao.common.CommonDao;
import cn.tedu.entity.User;
import cn.tedu.vo.CountVO;
import cn.tedu.vo.UserRole;
/**
 * UserDao接口的子实现一
 * @author Administrator
 *
 */
public class UserDaoImpl implements UserDao{

	@Override
	public String login(User user)throws Exception{
		String id=null;
		String sql="select user_id id from t_user "
				+ "where user_loginname=? and "
				+ "user_password=?";
		Object[] params=new Object[] {
				user.getLoginName(),
				user.getPassword()
		};
		List<User> users=CommonDao.executeQuery(User.class,sql,params);
		if(users!=null && users.size()==1) {
			id=users.get(0).getId();
		}
		return id;
	}

	@Override
	public int getCount(String userkeyword)throws Exception {
		int count=0;
		//是对用户做分页,所以需要查询指定模糊条件的总记录数
		String sql="select count(user_id) geshu from t_user "
				+ "where user_nickName like ? or "
				+ "user_loginname like ? ";
		List<CountVO> countVOs=CommonDao.executeQuery(CountVO.class, sql, "%"+userkeyword+"%","%"+userkeyword+"%");
		if(countVOs!=null && countVOs.size()==1) {
			count=countVOs.get(0).getGeshu();
		}
		return count;
	}

	@Override
	public List<UserRole> getUserRolesByPage(int currentPage, int pageSize, String userkeyword) throws Exception {
		List<UserRole> userRoles=null;
		String sql="select "
				+ "u.user_id id, "
				+ "u.user_loginname loginName, "
				+ "+++u.user_nickname nickName, "
				+ "u.user_logintype loginType, "
				+ "u.user_score score, "
				+ "u.user_regdate regDate, "
				+ "u.user_islock isLock, "
				+ "r.role_id roleId, "
				+ "r.role_name roleName "
		     + "from (select * from t_user "
				    + "where user_nickname like ? or "
				          + "user_loginname like ? "
				     + "limit ?,? "
				   + ") u "
			 + "left outer join t_user_role ur on u.user_id=ur.uid "
			 + "left outer join t_role r on r.role_id=ur.rid";
		Object[] params=new Object[] {
			"%"+userkeyword+"%",
			"%"+userkeyword+"%",
			(currentPage-1)*pageSize,
			pageSize
		};
		userRoles=CommonDao.executeQuery(UserRole.class, sql, params);
		return userRoles;
	}

	@Override
	public int addUser(User user)throws Exception {
		int rowAffect=0;
		String sql="insert into t_user(user_id,user_loginname,user_password,user_nickname,user_age,user_sex,user_head)values(?,?,?,?,?,?,?)";
		Object[] params=new Object[] {
				user.getId(),
				user.getLoginName(),
				user.getPassword(),
				user.getNickName(),
				user.getAge(),
				user.getSex(),
				user.getHead()
		};
		rowAffect=CommonDao.executeUpdate(sql, params);
		return rowAffect;
	}

	@Override
	public int addUserRole(String id, String roleId)throws Exception {
		int rowAffect=0;
		String sql="insert into t_user_role(uid,rid)value(?,?)";
		rowAffect=CommonDao.executeUpdate(sql, id,roleId);
		return rowAffect;
	}

}
